package org.sanguine.study.hometasks.second;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.sanguine.study.hometasks.first.TaskWorker;

public class Task1 implements TaskWorker {
	private String fileName;
	private File file;
	private List<String> text = new ArrayList<>();

	public static void main(String[] args) {
		TaskWorker task = new Task1();
		
		if (task.setUp(null, null, args)) {
			task.doTask();
		} else {
			System.err.println("Setup failed");
		}
	}

	private void printUsage() {
		System.err.println("USAGE: java -jar Task1.jar 'fileName'");
	}

	@Override
	public boolean setUp(Reader in, PrintWriter out, String[] args) {
		if (args == null || args.length < 1) {
			printUsage();
			return false;
		}
		fileName = args[0];
		file = new File(fileName);
		if (file.isFile()) return true;
		
		System.err.printf("File %s is not file or does not exist%n", fileName);
		file = null;
		return false;
	}

	@Override
	public void doTask() {
		if (file == null) return;

		try (Reader in = new FileReader(file)) {
			Scanner scanner = new Scanner(in);
			while (scanner.hasNextLine()) text.add(scanner.nextLine());
			scanner.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		try (PrintWriter out = new PrintWriter(file)) {
			for (int i = text.size() - 1; i >= 0; i--) out.println(text.get(i));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
